package com.tgy.esp32Service.dto;

import com.tgy.esp32Service.constant.CommonConsts;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;

import java.io.Serializable;

/***
 * @ClassName: R
 * @Description: 通用实体类返回
 * @Auther: tanggy3
 * @Date: 15:24 2022/9/14
 * @version : V1.0
 */
@Data
@ToString
@Accessors(chain = true)
@ApiModel(value = "R对象", description = "接口返回通用结构体")
public class R<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 兼容旧代码属性
     */
    @ApiModelProperty("返回状态：成功返回success")
    private String status;

    @ApiModelProperty("返回编码：成功返回0，失败返回1")
    private String code;

    @ApiModelProperty("消息提示")
    private String message;

    @ApiModelProperty("业务数据信息")
    private T data;

    @ApiModelProperty("是否成功")
    public boolean getSuccess() {
        return CommonConsts.SUCCESS.equals(code) || CommonConsts.SUCCESS_STR.equals(status);
    }

    // ----------------------- 正常返回（成功失败） ------------------------------
    public static <T> R<T> ok() {
        return restResult(null, CommonConsts.SUCCESS, CommonConsts.SUCCESS_TIP);
    }

    public static <T> R<T> ok(T data) {
        return restResult(data, CommonConsts.SUCCESS, CommonConsts.SUCCESS_TIP);
    }

    public static <T> R<T> ok(T data, String msg) {
        return restResult(data, CommonConsts.SUCCESS, msg);
    }

    public static <T> R<T> failed() {
        return restResult(null, CommonConsts.FAIL, CommonConsts.FAIL_TIP);
    }

    public static <T> R<T> failed(String msg) {
        return restResult(null, CommonConsts.FAIL, msg);
    }

    public static <T> R<T> failed(T data) {
        return restResult(data, CommonConsts.FAIL, CommonConsts.FAIL_TIP);
    }

    public static <T> R<T> failed(T data, String msg) {
        return restResult(data, CommonConsts.FAIL, msg);
    }

    protected static <T> R<T> restResult(T data, String code, String msg) {
        R<T> r = new R<>();
        r.setCode(code);
        r.setData(data);
        r.setMessage(msg);
        if (r.getSuccess()) {
            r.setStatus(CommonConsts.SUCCESS_STR);
        }
        return r;
    }

}
